package org.example.controller;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.CheckUtils;
import org.example.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public Result getUser(@PathVariable int id,@RequestHeader String token) {
        Claims claims = JWTUtils.parseToken(token);
        if(!CheckUtils.checkPermissionInUserTable(id, claims))
            return Result.error("该用户没有权限");
        User user = userService.getUserInfoById(id);
        if(user == null)
            return Result.error("用户不存在");
        return Result.success(user);
    }

    @PutMapping(value = "/{id}", consumes = "multipart/form-data")
    public Result updateUser(@PathVariable int id,@RequestHeader String token,
                             @RequestPart(value = "name", required = false) String name,
                             @RequestPart(value = "password", required = false) String password,
                             @RequestPart(value = "image", required = false) MultipartFile imageFile,
                             @RequestPart(value = "birthday", required = false) LocalDate birthday,
                             @RequestPart(value = "grade" , required = false) String grade,
                             @RequestPart(value = "major", required = false) String major,
                             @RequestPart(value = "classId", required = false) String classId,
                             @RequestPart(value = "classRole", required = false) String classRole) {
        Claims claims = JWTUtils.parseToken(token);
        if(!CheckUtils.checkPermissionInUserTable(id, claims))
            return Result.error("该用户没有权限");
        User user = new User(id, name, password, null, birthday,null, grade, major, classId, classRole, null, null);

        if(userService.update(user, imageFile))
            return Result.success();
        return Result.error("用户名重复");
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable int id,@RequestHeader String token) {
        Claims claims = JWTUtils.parseToken(token);
        if(!CheckUtils.checkPermissionInUserTable(id, claims))
            return Result.error("该用户没有权限");
        if(userService.delete(id))
            return Result.success();
        return Result.error("用户不存在");
    }
}
